package com.jingyuan.biz.server;

import com.jingyuan.biz.manager.JNodeManager;
import com.jingyuan.common.entity.utils.SpringUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
@Setter
public class NettyHarmonyServer {
    @Autowired
    private ServerEventHandler handler;
    @Autowired
    private TestHandler testHandler;
    private int port;
    public void start() throws InterruptedException {
        startCheckSuiviveSchedule();
        //final EchoServerHandler handler=new EchoServerHandler();
        EventLoopGroup group=new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap=new ServerBootstrap();
            serverBootstrap.group(group)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new ObjectDecoder(1024*1024,
                                    ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
                            socketChannel.pipeline().addLast(new ObjectEncoder());
                            //socketChannel.pipeline().addLast(handler);
                            socketChannel.pipeline().addLast(handler);
                        }
                    });
            ChannelFuture f = serverBootstrap.bind().sync();
            f.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully().sync();
        }
    }

    private void startCheckSuiviveSchedule(){
        JNodeManager nodeManager=SpringUtil.getBean(JNodeManager.class);
        //每4秒检查一下机器是否存活
        ScheduledExecutorService scheduledExecutorService=(ScheduledExecutorService) Executors.newScheduledThreadPool(1);
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
               nodeManager.checkNodeIslive();
            }
        },2,4,TimeUnit.SECONDS);
    }
}
